import 'package:flutter/material.dart';
import 'package:myapp/bean/category.dart';
import 'package:myapp/ui/item/item_article_widget_2.dart';
import 'package:myapp/util/colors_utils.dart';
import 'package:myapp/view_model/system_page_model.dart';
import 'package:myapp/widget/loading_container.dart';
import 'package:myapp/widget/provider_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SystemPage extends StatefulWidget {
  const SystemPage({Key key}) : super(key: key);

  @override
  _SystemPageState createState() => _SystemPageState();
}

class _SystemPageState extends State<SystemPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController _tabController;
  ViewState _viewState = ViewState.loading;

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<SystemPageModel>(
        model: SystemPageModel(),
        onModelInit: _loadCategory,
        builder: (context, model, child) {
          return Scaffold(
            appBar: AppBar(
              title: Center(
                  child: Text(
                "体系",
                style: TextStyle(
                  color: ColorUtils.color_text_1,
                  fontSize: 15,
                ),
              )),
              bottom: _tabController != null
                  ? TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      physics: AlwaysScrollableScrollPhysics(),
                      indicatorColor: ColorUtils.color_text_1,
                      tabs: []
                        ..addAll(model.getArticleCategories.map((e) => Tab(
                              text: e.name,
                            ))),
                    )
                  : null,
            ),
            body: LoadingContainer(
              retry: () => _loadCategory(model),
              child: TabBarView(
                controller: _tabController,
                physics: AlwaysScrollableScrollPhysics(),
                children: []
                  ..addAll(model.getArticleCategories.map((e) => SystemListPage(
                        tags: e.children,
                      ))),
              ),
              viewState: _viewState,
            ),
          );
        });
  }

  _loadCategory(model) async {
    _viewState = ViewState.loading;
    await model.loadArticleCategories((categorys) {
      if (categorys.isNotEmpty) {
        _viewState = ViewState.content;
        _tabController = TabController(length: categorys.length, vsync: this);
      } else {
        _viewState = ViewState.error;
      }
    });
  }

  @override
  bool get wantKeepAlive => true;
}

class SystemListPage extends StatefulWidget {
  final List<Category> tags;

  const SystemListPage({Key key, @required this.tags}) : super(key: key);

  @override
  _SystemListPageState createState() => _SystemListPageState();
}

class _SystemListPageState extends State<SystemListPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  @override
  Widget build(BuildContext context) {
    return ProviderWidget(
        model: SystemPageModel(),
        onModelInit: (model) {
          if (widget.tags.isNotEmpty) {
            model.chooseTag(widget.tags[0].id);
          }
        },
        builder: (context, model, child) => Column(
              children: [
                if (widget.tags.isNotEmpty) _getTag(model),
                Expanded(
                    child: SmartRefresher(
                  physics: BouncingScrollPhysics(),
                  controller: _refreshController,
                  onRefresh: () => _onRefresh(model),
                  onLoading: () => _onLoading(model),
                  enablePullDown: true,
                  enablePullUp: model.getArticles.isNotEmpty,
                  header: WaterDropHeader(),
                  child: ListView.separated(
                      itemBuilder: (context, index) => ItemArticleWidget2(
                            article: model.getArticles[index],
                          ),
                      separatorBuilder: (context, index) => Divider(height: 4),
                      itemCount: model.getArticles.length),
                ))
              ],
            ));
  }

  _onRefresh(model) async {
    await model.refresh();
    _refreshController.refreshCompleted();
    if (model.isLoadMore) {
      _refreshController.resetNoData();
    }
  }

  _onLoading(model) async {
    await model.loadMore();
    if (model.isLoadMore) {
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  _getTag(model) {
    var tags = widget.tags;
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10),
      margin: EdgeInsets.only(bottom: 1),
      child: SizedBox(
          height: 26,
          child: ListView.separated(
              itemCount: tags.length,
              separatorBuilder: (context, index) => VerticalDivider(
                    width: 12,
                    color: Colors.transparent,
                  ),
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) => InkWell(
                    child: Container(
                      child: Center(
                          child: Padding(
                        child: Text(
                          tags[index].name,
                        ),
                        padding: EdgeInsets.symmetric(horizontal: 10),
                      )),
                      decoration: BoxDecoration(
                          color: model.chooseId == tags[index].id
                              ? ColorUtils.color_bg_3
                              : ColorUtils.color_bg_2,
                          borderRadius: BorderRadius.circular(24)),
                    ),
                    onTap: () {
                      model.chooseTag(tags[index].id);
                      _refreshController.requestRefresh();
                    },
                  ))),
      color: ColorUtils.color_bg_1,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
